import json
import logging
import os
from pathlib import Path

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('file_operation.log', encoding='utf-8'),
    ]
)
logger = logging.getLogger("FileHandler")


class FileHandler:
    def __init__(self, base_dir=r"D:\work\pythonProject\bao"):
        self.base_dir = base_dir
        Path(self.base_dir).mkdir(parents=True, exist_ok=True)
        logger.info(f"初始化文件处理器，基础目录: {self.base_dir}")

    def read_text(self, filename, encoding='utf-8'):
        file_path = os.path.join(self.base_dir, filename)
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            logger.info(f"成功读取文本文件: {file_path}")
            return content
        except FileNotFoundError:
            logger.error(f"读取失败，文件不存在: {file_path}")
            raise
        except PermissionError:
            logger.error(f"读取失败，没有权限访问: {file_path}")
            raise
        except UnicodeDecodeError:
            logger.error(f"读取失败，编码错误({encoding}): {file_path}")
            raise
        except Exception as e:
            logger.error(f"读取文本文件发生未知错误 {file_path}: {str(e)}")
            raise

    def write_text(self, filename, content, mode='a', encoding='utf-8'):
        file_path = os.path.join(self.base_dir, filename)
        try:
            with open(file_path, mode, encoding=encoding) as f:
                f.write(content)
            logger.info(f"成功写入文本文件: {file_path} (模式: {mode})")
        except PermissionError:
            logger.error(f"写入失败，没有权限: {file_path}")
            raise
        except Exception as e:
            logger.error(f"写入文本文件发生未知错误 {file_path}: {str(e)}")
            raise

    def read_binary(self, filename):
        file_path = os.path.join(self.base_dir, filename)
        try:
            with open(file_path, 'rb') as f:
                content = f.read()
            logger.info(f"成功读取二进制文件: {file_path}")
            return content
        except FileNotFoundError:
            logger.error(f"读取失败，二进制文件不存在: {file_path}")
            raise
        except Exception as e:
            logger.error(f"读取二进制文件发生未知错误 {file_path}: {str(e)}")
            raise

    def copy_binary(self, source_filename, target_filename, target_dir=r"F:\work\homework\bao"):
        source_path = os.path.join(self.base_dir, source_filename)
        target_path = os.path.join(target_dir, target_filename)

        Path(target_dir).mkdir(parents=True, exist_ok=True)

        try:
            with open(source_path, 'rb') as src:
                content = src.read()
            with open(target_path, 'wb') as dst:
                dst.write(content)

            logger.info(f"成功复制二进制文件: {source_path} -> {target_path}")
        except FileNotFoundError:
            logger.error(f"复制失败，源文件不存在: {source_path}")
            raise
        except Exception as e:
            logger.error(f"复制二进制文件发生错误: {str(e)}")
            raise

    def dict_to_json_str(self, data):
        try:
            json_str = json.dumps(data, ensure_ascii=False)
            logger.info("成功将字典转换为JSON字符串")
            return json_str
        except TypeError as e:
            logger.error(f"字典转换JSON失败，数据类型错误: {str(e)}")
            raise
        except Exception as e:
            logger.error(f"字典转换JSON发生未知错误: {str(e)}")
            raise

    def json_str_to_dict(self, json_str):
        try:
            data = json.loads(json_str)
            logger.info("成功将JSON字符串转换为字典")
            return data
        except json.JSONDecodeError as e:
            logger.error(f"JSON字符串解析失败: {str(e)}")
            raise
        except Exception as e:
            logger.error(f"JSON转换字典发生未知错误: {str(e)}")
            raise

    def dict_to_json_file(self, data, filename):
        file_path = os.path.join(self.base_dir, filename)
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            logger.info(f"成功将字典写入JSON文件: {file_path}")
        except Exception as e:
            logger.error(f"字典写入JSON文件失败 {file_path}: {str(e)}")
            raise


if __name__ == '__main__':
    file_handler = FileHandler()

    try:
        test_data = {"ahn": "hsan", "han": "kun"}
        file_handler.dict_to_json_file(test_data, 'cls2.txt')

        content1 = file_handler.read_text('cls1.txt')
        print(f"cls1.txt内容: {content1}")

        content2 = file_handler.read_text('cls2.txt')
        print(f"cls2.txt内容: {content2}")

        # binary_data = file_handler.read_binary('jjj.png')
        # file_handler.copy_binary('jjj.png', 'copied_jjj.png')

    except Exception as e:
        logger.critical(f"程序执行出错: {str(e)}", exc_info=True)
